<?php
/**
 * Created by PhpStorm.
 * User: 13469
 * Date: 2018/12/11
 * Time: 12:02
 */
include "config.php";
if($_SERVER["REQUEST_METHOD"]=="POST"){
$UID=$_REQUEST["u_id"];
$GID=$_REQUEST["cid"];
$CNAME=$_REQUEST["ctitle"];
$CPRICE=$_REQUEST["cprice"];
$CNUM=$_REQUEST["num"];
$CTOTAL=$CNUM*$CPRICE;
$sql="SELECT *FROM carts WHERE u_id=?;";
$stmt=$conn->prepare($sql);
$stmt->bind_param("i",$UID);
$stmt->execute();
$qResult=$stmt->get_result();
$flag=true; //默认没有
    //没有就添加一条数据、
    //有 就数量和金额修改
    while ($row=$qResult->fetch_assoc()){
        if($row["g_id"]==$GID){
            $flag=false;
            break;
        }
    }
    if($flag==true){
        //没有购买 添加购买记录
        $sqlInert="INSERT INTO carts (`c_name`,`c_price`,`c_num`,`c_total`,`g_id`,`u_id`)VALUES(?,?,?,?,?,?)";
        $stmtI=$conn->prepare($sqlInert);
        $stmtI->bind_param("ssiiii",$CNAME,$CPRICE,$CNUM,$CTOTAL,$GID,$UID);
        $stmtI->execute();
        if($stmtI->affected_rows>=1){
            print_r(json_encode(array("status"=>1,"msg"=>"加入购物车成功I")));
        }else{
            print_r(json_encode(array("status"=>-1,"msg"=>"加入购物车失败I")));
        }
    }else{
        //有购买数据， 就修改数量及金额
        $sqlUpdate="UPDATE carts SET c_num=c_num+?,c_total=c_num*c_price WHERE u_id=? AND g_id=?";
        $stmtU=$conn->prepare($sqlUpdate);
        $stmtU->bind_param("iii",$CNUM,$UID,$GID);
        $stmtU->execute();
        if($stmtU->affected_rows>=1){
            print_r(json_encode(array("status"=>1,"msg"=>"加入购物车成功U")));
        }else{
            print_r(json_encode(array("status"=>-1,"msg"=>"加入购物车失败U")));
        }
    }

}else{
    print_r(json_encode(array("status"=>0,"msg"=>"不主持get请求")));

}
$conn->close();